/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.*;
import org.hibernate.*;
import pojo.Danhmuc;
import pojo.Donvi;
import pojo.Sanpham;
import util.HibernateUtil;

/**
 *
 * @author Quan
 */
public class SanPhamDAO extends TableDAO {

    public SanPhamDAO() {
        hql_laydanhsach = "from Sanpham";
        hql_lay = "from Sanpham where id = :id";
    }

    public static List<Sanpham> Tim(Map<String, Object> map) {
        List ds = null;

        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        String hql = "from Sanpham s where 1=1 ";

        if (((String) map.get("masp")).length() > 0) {
            hql += "and s.masanpham like :masanpham ";
        }
        if (((String) map.get("ten")).length() > 0) {
            hql += "and s.tensanpham like :tensanpham ";
        }
        if (map.get("sltonlonhon") != null) {
            hql += "and s.soluongton >= " + map.get("sltonlonhon") + " ";
        }
        if (map.get("sltonnhohon") != null) {
            hql += "and s.soluongton <= " + map.get("sltonnhohon") + " ";
        }
        if (map.get("danhmuc") != null) {
            hql += "and s.danhmuc = " + String.valueOf(((Danhmuc) map.get("danhmuc")).getId()) + " ";
        }
        if (map.get("donvi") != null) {
            hql += "and s.donvi = " + String.valueOf(((Donvi) map.get("donvi")).getId()) + " ";
        }

        try {
            org.hibernate.Query query = session.createQuery(hql);
            if (((String) map.get("masp")).length() > 0) {
                query.setParameter("masanpham", "%" + map.get("masp") + "%");
            }
            if (((String) map.get("ten")).length() > 0) {
                query.setParameter("tensanpham", "%" + map.get("ten") + "%");
            }
            ds = query.list();
        } catch (SessionException e) {
            throw new QueryException(hql);
        } finally {
            session.close();
        }
        return ds;
    }
    
    public List LayDanhSach(Danhmuc danhmuc) throws Exception {
        List ds = null;
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        String hql = "from Sanpham where danhmuc = :danhmuc";
        try {
            org.hibernate.Query query = session.createQuery(hql);
            query.setParameter("danhmuc", danhmuc);
            ds = query.list();
        } catch (SessionException e) {
            throw new QueryException(e.getMessage());
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        } finally {
            session.close();
        }
        return ds;
    }
}
